﻿using System;
using System.Collections.Generic;
using System.Linq;

using Perseus;

namespace Hetymine.Executioner.Data {
    public class ParameterInfo {
        public ParameterInfo() {
            this.Flags = new Dictionary<string, FlagInfo>();
            this.Parameters = new List<string>();
        }
        public ParameterInfo(string parameters) {
            this.Flags = new Dictionary<string, FlagInfo>();
            this.Parameters = new List<string>();

            SkipStringStream skip = new SkipStringStream();
            skip.AddSkipItem(new SkipItem("[", "]"));
            SkipItem skipItem = new SkipItem("\"", "\"", 1);
            skipItem.IgnoreStrings = new string[] { "\\\"" };
            skip.AddSkipItem(skipItem);

            string[] prams = parameters.Split(" ", skip, SplitOptions.RemoveEmptyEntries);

            if (prams.Length > 0 && prams[0].StartsWith("-", StringComparison.Ordinal)) {
                int len = prams[0].Length - 1;
                for (int i = 1; i <= len; ++i) {
                    FlagInfo f = new FlagInfo(prams[0][i].ToString());

                    if (i != len && prams[0][i + 1] == '[') {
                        int pos = prams[0].IndexOf(']', i + 1);
                        // No closing bracket so ignore it so it gets treated as regular flag
                        if (pos < 0) {
                            continue;
                        }

                        string[] flagParameters = prams[0].Substring(i + 2, pos - i - 2).Split(
                            ",", 
                            skip, 
                            SplitOptions.RemoveEmptyEntries | SplitOptions.Trim
                        );

                        f.Parameters.AddRange(flagParameters);
                        i = pos;
                    }

                    this.Flags.Add(f.Flag, f);
                }

                PArray.RemoveItem(ref prams, 0);
            }

            foreach (string p in prams) {
                if (p.EnclosedWith("\"", "\"", StringComparison.Ordinal)) {
                    this.Parameters.Add(p.Substring(1, p.Length - 2));
                }
                else {
                    this.Parameters.Add(p);
                }
            }
        }

        public Dictionary<string, FlagInfo> Flags { get; set; }
        public List<string> Parameters { get; set; }
        public bool HasFlags(string flags) {
            for (int i = 0; i < flags.Length; ++i) {                
                if (!this.Flags.ContainsKey(flags[i].ToString())) {
                    return false;
                }
            }

            return true;
        }
        public bool IsEmpty { 
            get { return (this.Parameters.Count == 0); } 
        }
    }
}
